<template>
  <div class="app-container">
    <el-form ref="blogForm" :model="blogForm" label-width="120px" :rules="rules">
      <el-form-item label="标题" prop="title">
        <el-input v-model="blogForm.title" placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <!-- @blur="onEditorBlur($event)" @focus="onEditorFocus($event)" @ready="onEditorReady($event)"  -->
        <quill-editor ref="myQuillEditor" :options="editorOption" v-model="blogForm.content" />
      </el-form-item>
      <el-form-item label="声明" prop="flag">
        <el-select v-model="blogForm.flag" placeholder="请选择">
          <el-option label="原创" value="原创"> </el-option>
          <el-option label="转载" value="转载"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="分类" prop="typeId">
        <el-select v-model="blogForm.typeId" placeholder="请选择分类">
          <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="首图引用地址" prop="firstPicture">
        <el-input v-model="blogForm.firstPicture" placeholder="请输入首图引用地址" />
      </el-form-item>
      <el-form-item label="摘要" prop="description">
        <el-input v-model="blogForm.description" type="textarea" placeholder="请输入文章摘要" maxlength="100" show-word-limit />
      </el-form-item>
      <el-form-item label="设置">
        <el-checkbox v-model="blogForm.recommend">推荐</el-checkbox>
        <el-checkbox v-model="blogForm.shareStatement">转载</el-checkbox>
        <el-checkbox v-model="blogForm.appreciation">赞赏</el-checkbox>
        <el-checkbox v-model="blogForm.commentabled">评论</el-checkbox>
        <el-checkbox v-model="blogForm.published">发布</el-checkbox>
      </el-form-item>
    </el-form>
    <div style="text-align: center">
      <el-button type="danger" @click="cancle()">取消</el-button>
      <el-button v-if="blogForm.id" type="primary" @click="update('blogForm')">更新</el-button>
      <el-button v-else type="primary" @click="save('blogForm')">保存</el-button>
    </div>
  </div>
</template>
<script>
import productTypeApi from '@/api/type'
import blogApi from '@/api/blog'

// 工具栏配置
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
  ['blockquote', 'code-block'], // 引用  代码块-----['blockquote', 'code-block']
  [{ header: 1 }, { header: 2 }], // 1、2 级标题-----[{ header: 1 }, { header: 2 }]
  [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
  [{ script: 'sub' }, { script: 'super' }], // 上标/下标-----[{ script: 'sub' }, { script: 'super' }]
  [{ indent: '-1' }, { indent: '+1' }], // 缩进-----[{ indent: '-1' }, { indent: '+1' }]
  [{ direction: 'rtl' }], // 文本方向-----[{'direction': 'rtl'}]
  [{ size: ['small', false, 'large', 'huge'] }], // 字体大小-----[{ size: ['small', false, 'large', 'huge'] }]
  [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题-----[{ header: [1, 2, 3, 4, 5, 6, false] }]
  [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色-----[{ color: [] }, { background: [] }]
  [{ font: [] }], // 字体种类-----[{ font: [] }]
  [{ align: [] }], // 对齐方式-----[{ align: [] }]
  ['clean'], // 清除文本格式-----['clean']
  ['link', 'image', 'video'] // 链接、图片、视频-----['link', 'image', 'video']
]

const defaultForm = {
  id: '',
  flag: '原创',
  title: '',
  content: '',
  typeId: '',
  description: '',
  firstPicture: '',
  recommend: true,
  shareStatement: true,
  commentabled: true,
  appreciation: true,
  published: true,
  views: 0
}

export default {
  data() {
    return {
      // 富文本编辑器
      editorOption: {
        placeholder: '写点什么吧...',
        theme: 'snow',
        modules: {
          toolbar: {
            container: toolbarOptions
          },
          imageDrop: true, //图片拖拽
          imageResize: {
            //放大缩小
            displayStyles: {
              backgroundColor: 'black',
              border: 'none',
              color: 'white'
            },
            modules: ['Resize', 'DisplaySize', 'Toolbar']
          }
        }
      },
      typeList: [],
      blogForm: defaultForm,
      // 表单验证
      rules: {
        title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        content: [{ required: true, message: '内容不能为空', trigger: 'change' }],
        typeId: [{ required: true, message: '分类不能为空', trigger: 'change' }],
        flag: [{ required: true, message: '声明不能为空', trigger: 'change' }],
        description: [{ required: true, message: '文章摘要不能为空', trigger: 'change' }]
      }
    }
  },
  // watch的作用可以监控一个值的变换,并调用因为变化需要执行的方法。
  //监听路由是否发生变化
  watch: {
    $route(to, from) {
      console.log(to, from)
      //当监听的路由这个方法执行的时候，
      //我们是不是判断此路由过来的参数是否存在，
      //如果不存在，那就说明是新增
      //如果存在那么说明修改过来的
      this.init()
    }
  },
  created() {
    this.init()
    this.getType()
  },
  methods: {
    // 页面初始化，判断是新增还是编辑
    init() {
      // 判断是否有参数
      if (this.$route.params && this.$route.params.id) {
        // 当加载页面的时候就要获取参数的值了
        this.selectById(this.$route.params.id)
      } else {
        // 没有参数 清空
        this.blogForm = { ...defaultForm }
        console.log(this.blogForm)
      }
    },

    // 根据id查询文章
    selectById(id) {
      blogApi.getById(id).then(response => {
        if (response.code === 20000) {
          this.blogForm = response.data.data
        } else {
          this.$message.error(response.message)
        }
      })
    },

    // 分类
    getType() {
      productTypeApi.list().then(response => {
        if (response.code === 20000) {
          this.typeList = response.data.data
        } else {
          this.$message.error(response.message)
        }
      })
    },

    // 取消
    cancle() {
      this.$router.push('/article/articleList')
    },

    // 添加博客
    save(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // 博客端内容回显时，代码高亮及添加行号使用：
          // 由于我们通过富文本编辑器生成的代码结构只有pre标签,
          // 而prismjs代码高亮插件只对pre标签嵌套的code标签起作用,
          // 有的类名必须写在code标签上,所以我们在存进数据库之前要做一个全局替换工作.
          // 类名line-numbers显示行号language-xxx选择编程语言，这里我们选择js：language-js
          let newContent = this.blogForm.content.replace(/<pre class="ql-syntax" spellcheck="false">/g, '<pre class="ql-syntax line-numbers language-js" spellcheck="false"><code class="language-js">')
          newContent = newContent.replace(/<\/pre>/g, '</code></pre>')

          const form = new FormData()
          form.append('id', this.blogForm.id)
          form.append('userId', JSON.parse(localStorage.getItem('userInfo')).id)
          form.append('flag', this.blogForm.flag)
          form.append('title', this.blogForm.title)
          form.append('content', newContent)
          form.append('typeId', this.blogForm.typeId)
          form.append('recommend', this.blogForm.recommend)
          form.append('description', this.blogForm.description)
          form.append('firstPicture', this.blogForm.firstPicture)
          form.append('shareStatement', this.blogForm.shareStatement)
          form.append('commentabled', this.blogForm.commentabled)
          form.append('appreciation', this.blogForm.appreciation)
          form.append('published', this.blogForm.published)
          form.append('views', this.blogForm.views)

          blogApi.save(form).then(response => {
            if (response.code === 20000) {
              this.$message.success(response.message)
              this.$router.push('/article/articleList')
            } else {
              this.$message.error(response.message)
            }
          })
        }
      })
    },

    // 更新博客
    update(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // 博客端内容回显时，代码高亮及添加行号使用：
          // 由于我们通过富文本编辑器生成的代码结构只有pre标签,
          // 而prismjs代码高亮插件只对pre标签嵌套的code标签起作用,
          // 有的类名必须写在code标签上,所以我们在存进数据库之前要做一个全局替换工作.
          // 类名line-numbers显示行号language-xxx选择编程语言，这里我们选择js：language-js
          let newContent = this.blogForm.content.replace(/<pre class="ql-syntax" spellcheck="false">/g, '<pre class="ql-syntax line-numbers language-js" spellcheck="false"><code class="language-js">')
          newContent = newContent.replace(/<\/pre>/g, '</code></pre>')

          const form = new FormData()
          form.append('id', this.blogForm.id)
          form.append('userId', JSON.parse(localStorage.getItem('userInfo')).id)
          form.append('flag', this.blogForm.flag)
          form.append('title', this.blogForm.title)
          form.append('content', newContent)
          form.append('typeId', this.blogForm.typeId)
          form.append('recommend', this.blogForm.recommend)
          form.append('description', this.blogForm.description)
          form.append('firstPicture', this.blogForm.firstPicture)
          form.append('shareStatement', this.blogForm.shareStatement)
          form.append('commentabled', this.blogForm.commentabled)
          form.append('appreciation', this.blogForm.appreciation)
          form.append('published', this.blogForm.published)
          form.append('views', this.blogForm.views)

          blogApi.update(form).then(response => {
            if (response.code === 20000) {
              this.$message.success(response.message)
              this.$router.push('/article/articleList')
            } else {
              this.$message.error(response.message)
            }
          })
        }
      })
    }
  }
}
</script>
<style>
.ql-editor {
  line-height: normal !important;
  height: 800px !important ;
}
.ql-snow .ql-picker-label::before {
  position: relative;
  top: -10px;
}
.ql-toolbar.ql-snow .ql-picker.ql-expanded .ql-picker-label {
  border: 1px solid #5f5f5f;
}
.ql-toolbar.ql-snow .ql-picker-label {
  border: 1px solid #5f5f5f;
}
.ql-snow .ql-color-picker .ql-picker-label svg,
.ql-snow .ql-icon-picker .ql-picker-label svg {
  position: relative;
  right: 1px;
  top: -7px;
}
</style>
